package com.heima.wemedia.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/25
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;

    /**
     * 添加任务到延迟队列
     * @param id    文章id
     * @param publishTime   发布时间 --> 任务呀执行时间
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("leadnews-wemedia开始添加任务到延迟任务中。。。");
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClient.addTask(task);
        log.info("leadnews-wemedia已经添加任务到延迟任务中。。。");
    }

    @Autowired
    private WmNewsAutoScanService autoScanService;

    /**
     * 消费延迟队列中的数据
     * @Scheduled -->
     *      fixedRate = 1000  上一个任务开始时计时，一秒后执行下一个任务
     *      fixedDelay = 1000   上一个任务结束时计时，一秒后执行下一个任务
     */
    @Override
    //@Scheduled(fixedRate = 1000)
    @SneakyThrows   //Lombok异常抛出
    public void scanNewsByTask() {
        ResponseResult responseResult = scheduleClient.poll(
                TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (AppHttpCodeEnum.SUCCESS.getCode() == responseResult.getCode() &&
                ObjectUtil.isNotEmpty(responseResult.getData())) {
            String jsonStr = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(jsonStr, Task.class);
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            autoScanService.autoScanWmNews(wmNews.getId());
            log.info("拉取到文章审核消费任务，wmNewsId：{}", wmNews.getId());
        }
        //log.info("消费任务结束 --> 文章审核");
    }
}
